package com.putable.cgw.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JPanel;
/**
 * 
 * @author Todd
 *
 */
public class YardPanel extends JPanel {
	
	private Point mousePos = new Point(), cellPos = new Point();
	private YardPanel panel = this;
	{
		this.addMouseListener(new MouseAdapter(){
			@Override
			public void mouseReleased(MouseEvent e){
				if(e.getButton() == 1){
					mousePos = new Point(e.getX(), e.getY());
					panel.repaint();
					System.out.println("Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")" +
							" In Cell (" + cellPos.x + ", " + cellPos.y +")");
				}
			}
		});
	}
	private static final long serialVersionUID = 1L;
	@Override
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		
		Dimension cellSize = new Dimension(this.getSize().width/20, this.getSize().height/20);
		if(cellSize.width == 0 || cellSize.height == 0) 
			throw new ArithmeticException("Divides by zero: We can't let users resize applet");
		
		cellPos = new Point(mousePos.x / cellSize.width, mousePos.y/ cellSize.height);
		drawGrid(g, cellSize);
		drawRobot(g, cellSize, cellPos);
	}
	/**
	 * Draws the grid of the yard
	 * @param g The graphics of the DrawPanel
	 * @param cellSize The dimension of the cells size
	 */
	private void drawGrid(Graphics g, Dimension cellSize){
		g.setColor(new Color(0,0,0));
		for(int i = 0; i < 20; i++){
			g.drawLine(cellSize.width * i, 0, cellSize.width * i, this.getSize().height);
		}
		for(int j = 0; j < 20; j++){
			g.drawLine(0,cellSize.height * j, this.getSize().width, cellSize.height * j);
		}
		g.setColor(Color.BLACK);
		if(cellSize.width * 20 < this.getWidth())
			g.fillRect(cellSize.width * 20, 0, this.getWidth(), this.getHeight());
		if(cellSize.height * 20 < this.getHeight())
			g.fillRect(0, cellSize.height*20, this.getWidth(), this.getHeight());
		
	}
	/**
	 * Draws the Robot in the specified cell
	 * @param g The graphics of the yard
	 * @param cellSize The size of the cells
	 * @param pos The position of the robot
	 */
	private void drawRobot(Graphics g, Dimension cellSize, Point pos){
		
		g.setColor(Color.blue);
		//draws a blue rectangle in the cell you click on
		if(cellPos.x < 20 && cellPos.y < 20)
			g.fillRect(pos.x*cellSize.width, pos.y*cellSize.height, cellSize.width, cellSize.height);
	}

}
